<%@page language="java" import="java.sql.*" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages.recorrido"/>
<%
Integer userId=(Integer)request.getSession(false).getAttribute("id");
dbBean.DBConnectionManager connMgr=(dbBean.DBConnectionManager)application.getAttribute("connMgr");
if((userId==null) || (connMgr==null)) {
  application.log("- No existe una sesion de usuario o no se ha podido obtener una conexion con la BBDD");
%>
<html>
  <body onLoad="parent.location.href='/';">
  </body>
</html>
<%
} else {
String desde=(String)request.getParameter("desde");
String hasta=(String)request.getParameter("hasta");

if(desde==null)
        desde="";
if(hasta==null)
        hasta="";
Timestamp desdeTs=new Timestamp(0);
Timestamp hastaTs=new Timestamp(new java.util.Date().getTime());

if(desde!="") {
  try {
    desdeTs=Timestamp.valueOf(desde);
  } catch(IllegalArgumentException e) {e.printStackTrace();}
}
if(hasta!="") {
  try {
    hastaTs=Timestamp.valueOf(hasta);
  } catch(IllegalArgumentException e) {e.printStackTrace();}
}

Connection con=null;
StringBuffer datos=new StringBuffer();
 try {
  Timestamp timestamp=null;
  application.log("- Se va a consultar la ruta en la BBDD");
  con = connMgr.getConnection("mysql");
  PreparedStatement pstmt=null;
  if((desde=="") && (hasta=="")) {
      pstmt = con.prepareStatement("SELECT timestamp, latitud, longitud, velocidad, rumbo, altitud FROM datos WHERE UserId="+userId.toString()+" ORDER BY timestamp;");
  } else {
      pstmt = con.prepareStatement("SELECT timestamp, latitud, longitud, velocidad, rumbo, altitud FROM datos WHERE UserId="+userId.toString()+" AND timestamp BETWEEN ? AND ? ORDER BY timestamp;");
      pstmt.setTimestamp(1, desdeTs);
      pstmt.setTimestamp(2, hastaTs);
  }
  ResultSet rs=pstmt.executeQuery();
  while(rs.next()) {
      datos.append("#");
      timestamp=rs.getTimestamp(1);
      datos.append(timestamp.toString());
      datos.append(";");
      datos.append(rs.getString(2));
      datos.append(";");
      datos.append(rs.getString(3));
      datos.append(";");
      datos.append(rs.getString(4));
      datos.append(";");
      datos.append(rs.getString(5));
      datos.append(";");
      datos.append(rs.getString(6));
  }
  rs.close();
  pstmt.close();
  application.log("- Se ha obtenido la ruta correctamente");

} catch (SQLException e) {
  application.log("GoogleGPS_offline_descargar_VE.jsp",e);
}
if(con!=null)
  connMgr.freeConnection("mysql",con);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>GPSou</title>

<style type="text/css">
    .posinfo    {
                width: 220px;
                font-family: arial, sans-serif;
                color: #0000A0;
                font-size: 75%;
                font-stretch: narrower;
                font-weight: bold;
                text-align: left;
                }

.iconStyle
{
position:relative;
left:8px;
}
</style>

<script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2">
</script>

<script type="text/javascript">
//<![CDATA[

var markerCurrent;
var timer=setTimeout("", 0);
var posMarkerCurrent;

var tramoMedio;

var map;
var gMarker;
var ruta;
var latitudes, longitudes;
var points = [];
var datos="<%=datos.toString()%>";

function parseDate(str) {
  var ts=str.split(" ");
  var d=ts[0].split("-");
  var h=ts[1].split(":");
  var s=h[2].split(".");

  var fecha=new Date(Date.UTC(d[0], d[1] - 1, d[2], h[0], h[1], s[0], s[1]));

  return(fecha);
}

function fillDatos() {
      var results=parent.ruta[posMarkerCurrent].split(";");

      var fecha=parseDate(results[0]);
      var velocidad=Math.round(results[3] / 10);
      var altitud=results[5];

      parent.document.getElementById("fecha").innerHTML=fecha.toLocaleDateString();
      parent.document.getElementById("hora").innerHTML=fecha.toLocaleTimeString();
      parent.document.getElementById("velocidad").innerHTML=velocidad + " km/h";
      parent.document.getElementById("altitud").innerHTML=altitud + " m";
}

function drawMarker(position) {
}

function checkPoint(e) {
	var x=e.mapX;
	var y=e.mapY;
	var pixel=new VEPixel(x, y);
	var latLong=map.PixelToLatLong(pixel);
	var posLat=latLong.Latitude;
	var posLng=latLong.Longitude;
	var minDst=360;
	var dst;

	var inicio=0;
	var fin=parent.ruta.length-1;

	clearTimeout(timer);

	posMarkerCurrent=inicio;
	for(i=inicio;i<=fin;i++) {
		dst=Math.abs(parent.latitudes[i] - posLat) + Math.abs(parent.longitudes[i] - posLng);
		if(dst < minDst) {
			minDst=dst;
			posMarkerCurrent=i;
		}
	}
	
	markerCurrent.SetPoints([new VELatLong(latitudes[posMarkerCurrent], longitudes[posMarkerCurrent])]);
	timer=window.setTimeout("fillDatos();", 1000);

}


function load() {

        map = new VEMap('myMap');
	map.LoadMap();

	markerCurrent=new VEShape(VEShapeType.Pushpin, new VELatLong(0, 0));
	markerCurrent.SetCustomIcon('<div class="iconStyle"><img src="http://www.gpsou.es/VEGPS/html/images/redSquare.png" alt="icon"/></div>');

	map.SetMapMode(VEMapMode.Mode2D);
	map.SetMapStyle(VEMapStyle.Hybrid);

        ruta=datos.split("#");
        ruta.shift();
        tramoMedio=dibuja();
	map.AddShape(tramoMedio);
	map.AddShape(markerCurrent);
	distancia=calculaDistancia(0, parent.ruta.length-1);
	parent.document.getElementById("label").innerHTML="<fmt:message key="distance.text"/> <b>"+Math.round(distancia*1000)/1000+" km<\/b>";

        map.AttachEvent("onmousemove", checkPoint);

	map.SetMapView(tramoMedio.GetPoints());
}

function dibuja() {
    var point;
    var latitud, longitud, latitudNMEA, longitudNMEA;
    var grados;
    var polylineRuta;
    var results;

    try {
      fechas = new Array(ruta.length);
      latitudes = new Array(ruta.length);
      longitudes = new Array(ruta.length);

      for(i=0; i<parent.ruta.length; i++) {
        results=ruta[i].split(";");

        latitudNMEA=results[1];
        longitudNMEA=results[2];

        grados=Math.floor(latitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        latitud=(latitudNMEA/1000000-grados)/0.6+grados;
        grados=Math.floor(longitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        longitud=(longitudNMEA/1000000-grados)/0.6+grados;

	parent.fechas[i]=results[0];
	parent.latitudes[i]=latitud;
	parent.longitudes[i]=longitud;

        point = new VELatLong(latitud, longitud);
        points.push(point);
      }

      polylineRuta=new VEShape(VEShapeType.Polyline, points);
      polylineRuta.SetLineWidth(5);
      polylineRuta.SetLineColor(new VEColor(0, 0, 100, 0.5));
      polylineRuta.HideIcon();

    } catch (err) {alert("ERROR: "+err.description);}

    return(polylineRuta);
}

function calculaDistancia(startPoint, finishPoint) {
    var dx, dy;

    var dst=0;
    for(i=startPoint+1;i<=finishPoint;i++) {
        dx=6370*(parent.latitudes[i]-parent.latitudes[i-1])*Math.PI/180;
        dy=6370*Math.cos(parent.latitudes[i]*Math.PI/180)*(parent.longitudes[i]-parent.longitudes[i-1])*Math.PI/180;
        dst+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));
    }
    return(dst);
}

//]]>
</script>

</head>

<body onload="load()" onunload="map.Dispose()">


  <p style="text-align: center"><img src="http://www.gpsou.es/GoogleGPS/html/images/GPSou-logo-banner.png" alt="GPS-o&ugrave;"></p>
  <div style="text-align: center">
  <table style="margin-left: auto; margin-right: auto">
  <tr><td>
  <div id="myMap" style="position: relative; top: 0px; left: 0px; width: 500px; height: 300px; border: thick groove #A0A0FF"></div>
    <label id="label"> </label>

<form name="datosPerfil" action="null">
<p>
<input type="hidden" name="datosPerfil" value="hola">
</p>
</form>
  </td>
  <td valign="top">
    <form name="datos" action="null">
        <p>
        <fmt:message key="data.text"/> <img src="http://www.gpsou.es/GoogleGPS/html/images/redSquare.png" alt="cuadrado rojo">):
        <br>
        </p>
        <table>
        <tr><td><fmt:message key="data.date"/> </td><td class="posinfo"><span id="fecha" title="<fmt:message key="data.date.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.time"/> </td><td class="posinfo"><span id="hora" title="<fmt:message key="data.time.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.speed"/> </td><td class="posinfo"><span id="velocidad" title="<fmt:message key="data.speed.title"/>"> </span></td></tr>
        <tr><td><fmt:message key="data.altitude"/> </td><td class="posinfo"><span id="altitud" title="<fmt:message key="data.altitude.title"/>"> </span></td></tr>
        </table>
    </form>
  </td></tr>
  </table>
  <p>
    <img src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict" height="31" width="88">
  </p>
  </div>
</body>

</html>


<%
}
%>

